package com.atguigu.gmall.mq.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.mq.config.DeadLetterConfig;
import com.atguigu.gmall.mq.config.DelayedMqConfig;
import com.atguigu.gmall.rabbit.service.RabbitService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: atguigu
 * @create: 2023-08-11 11:40
 */
@RestController
@RequestMapping("/api/mq")
public class ProducerController {


    @Autowired
    private RabbitService rabbitService;


    /**
     * 模拟生产者发送普通消息到指定交换机
     *
     * @param msg
     * @return
     */
    @GetMapping("/sendNormalMsg")
    public Result sendNormalMsg(@RequestParam("msg") String msg) {
        String exhcange = "exchange.confirm";
        String routingKey = "routing.confirm";
        rabbitService.sendMsg(exhcange, routingKey, msg);
        return Result.ok();
    }


    /**
     * 发送死信消息-实现延迟
     *
     * @param msg
     * @return
     */
    @GetMapping("/sendDeadLetter")
    public Result sendDeadLetter(@RequestParam("msg") String msg) {
        rabbitService.sendMsg(DeadLetterConfig.exchange_dead, DeadLetterConfig.routing_dead_1, msg);
        return Result.ok();
    }

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 基于延迟插件-实现延迟
     *
     * @param msg
     * @param ttl 延迟时间 单位：s
     * @return
     */
    @GetMapping("/sendDelayMsg")
    public Result sendDelayMsg(@RequestParam("msg") String msg, @RequestParam("ttl") int ttl) {
        //1.调用模板对象发送消息-设置消息ttl过期时间
        //rabbitTemplate.convertAndSend(DelayedMqConfig.exchange_delay, DelayedMqConfig.routing_delay, msg, (message -> {
        //    //拿到MQ消息对象 为消息对象设置过期时间
        //    message.getMessageProperties().setDelay(ttl * 1000);
        //    return message;
        //}));
        //todo 调用工具方法发送延迟消息
        rabbitService.sendDelayMsg(DelayedMqConfig.exchange_delay, DelayedMqConfig.routing_delay, msg, ttl);
        return Result.ok();
    }
}
